Skip to content

Latest commit

 

History

History
48 lines (43 loc) · 1.06 KB

File metadata and controls

48 lines (43 loc) · 1.06 KB

59. Spiral Matrix II

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 

Solutions (Rust)

1. Simulation

implSolution{pubfngenerate_matrix(n:i32) -> Vec<Vec<i32>>{let n = n asusize;letmut ret = vec![vec![0; n]; n];letmut num = 1;for i in0..((n + 1) / 2){for c in i..(n - 1 - i){ ret[i][c] = num; num += 1;}for r in i..(n - 1 - i){ ret[r][n - 1 - i] = num; num += 1;}for c in((i + 1)..(n - i)).rev(){ ret[n - 1 - i][c] = num; num += 1;}for r in((i + 1)..(n - i)).rev(){ ret[r][i] = num; num += 1;}} ret[n / 2][(n - 1) / 2] = (n * n)asi32; ret }}
close